package com.example.cmh.service.impl;

import com.example.cmh.common.CustomException;
import com.example.cmh.common.PageResult;
import com.example.cmh.common.Result;
import com.example.cmh.mapper.CourseMapper;
import com.example.cmh.pojo.Course;
import com.example.cmh.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    @Transactional
    public Result<String> addCourse(Course course, Integer currentUserId) throws CustomException {
        if (course.getCourseName() == null || course.getCourseName().trim().isEmpty()) {
            throw new CustomException("课程名称不能为空");
        }
        if (course.getCourseIntro() == null || course.getCourseIntro().trim().isEmpty()) {
            throw new CustomException("课程简介不能为空");
        }
        if (course.getCourseSort() == null) {
            throw new CustomException("课程排序不能为空");
        }
        if (course.getCourseAuthor() == null || course.getCourseAuthor().trim().isEmpty()) {
            throw new CustomException("课程作者不能为空");
        }
        
        // 设置创建者ID
        course.setCreatePersonId(currentUserId);
        
        // 设置审核状态：管理员(ID=1)自动通过，其他用户需要审核
        if (currentUserId != null && currentUserId == 1) {
            course.setCourseStatus(1); // 已审核
        } else {
            course.setCourseStatus(0); // 未审核
        }
        
        int result = courseMapper.insert(course);
        if (result > 0) {
            return Result.success("新增课程成功", "success");
        } else {
            throw new CustomException("新增课程失败");
        }
    }

    @Override
    @Transactional
    public Result<String> updateCourse(Boolean isAdmin,Course course) throws CustomException {
        if (course.getCourseId() == null) {
            throw new CustomException("课程ID不能为空");
        }
        if (course.getCourseName() == null || course.getCourseName().trim().isEmpty()) {
            throw new CustomException("课程名称不能为空");
        }
        if (course.getCourseIntro() == null || course.getCourseIntro().trim().isEmpty()) {
            throw new CustomException("课程简介不能为空");
        }
        if (course.getCourseSort() == null) {
            throw new CustomException("课程排序不能为空");
        }
        if (course.getCourseAuthor() == null || course.getCourseAuthor().trim().isEmpty()) {
            throw new CustomException("课程作者不能为空");
        }
        
        Course old = courseMapper.selectById(course.getCourseId());
        if (old == null) {
            throw new CustomException("课程不存在");
        }
        if(Boolean.TRUE.equals(isAdmin)){
            course.setCourseStatus(1);
        }
        else course.setCourseStatus(0);
        int result = courseMapper.updateById(course);
        if (result > 0) {
            return Result.success("修改课程成功", "success");
        } else {
            throw new CustomException("修改课程失败");
        }
    }

    @Override
    @Transactional
    public Result<String> deleteCourse(Integer courseId) throws CustomException {
        if (courseId == null) {
            throw new CustomException("课程ID不能为空");
        }
        Course old = courseMapper.selectById(courseId);
        if (old == null) {
            throw new CustomException("课程不存在");
        }
        int result = courseMapper.deleteById(courseId);
        if (result > 0) {
            return Result.success("删除课程成功", "success");
        } else {
            throw new CustomException("删除课程失败");
        }
    }

    @Override
    public Result<List<Course>> searchCourse(String courseName, Integer courseSort, Integer currentUserId) throws CustomException {
        List<Course> list = courseMapper.selectByCondition(courseName, courseSort);
        
        // 过滤未审核的课程（普通用户只能看到自己的未审核课程）
        if (currentUserId != null && currentUserId != 1) {
            list.removeIf(course -> course.getCourseStatus() == 0 && !course.getCreatePersonId().equals(currentUserId));
        }
        
        return Result.success(list);
    }

    @Override
    public Result<Course> getCourseDetail(Integer courseId) throws CustomException {
        if (courseId == null) {
            throw new CustomException("课程ID不能为空");
        }
        Course course = courseMapper.selectById(courseId);
        if (course == null) {
            throw new CustomException("课程不存在");
        }
        return Result.success(course);
    }
    
    @Override
    public Result<PageResult<Course>> getCourseListWithPage(String courseName, Integer courseSort, Integer currentUserId, Integer current) throws CustomException {
        if (current == null || current < 1) {
            current = 1;
        }
        
        int pageSize = 10; // 固定每页10条
        int offset = (current - 1) * pageSize;
        
        // 确定查询条件
        Integer courseStatus = null;
        Integer createPersonId = null;
        
        if (currentUserId != null && currentUserId != 1) {
            // 普通用户：只显示已审核的课程或自己创建的未审核课程
            courseStatus = 1; // 已审核
            createPersonId = currentUserId; // 自己的未审核课程
        }
        // 管理员(currentUserId=1或null)可以看到所有课程
        
        List<Course> courseList = courseMapper.selectWithPage(courseName, courseSort, courseStatus, createPersonId, offset, pageSize);
        long total = courseMapper.count(courseName, courseSort, courseStatus, createPersonId);
        
        PageResult<Course> pageResult = new PageResult<>();
        pageResult.setRecords(courseList);
        pageResult.setTotal(total);
        pageResult.setCurrent(current);
        pageResult.setSize(pageSize);
        pageResult.setPages((int) Math.ceil((double) total / pageSize));
        
        return Result.success(pageResult);
    }
    
    @Override
    @Transactional
    public Result<String> reviewCourse(Integer courseId, Integer status) throws CustomException {
        if (courseId == null) {
            throw new CustomException("课程ID不能为空");
        }
        if (status == null || (status != 1 && status != 2)) {
            throw new CustomException("审核状态无效，1表示通过，2表示拒绝");
        }
        
        Course course = courseMapper.selectById(courseId);
        if (course == null) {
            throw new CustomException("课程不存在");
        }
        
        int result = courseMapper.updateStatus(courseId, status);
        if (result > 0) {
            String message = status == 1 ? "审核通过成功" : "审核拒绝成功";
            return Result.success(message, "success");
        } else {
            throw new CustomException("审核操作失败");
        }
    }
} 